package pckt.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

public class ConnectedThreadAndroid extends Thread{
	//Log
	private final String TAG = "pcktTest_connectedThread";
	private final static boolean D = true;
	
	private final BluetoothSocket sckt;
	private final InputStream in;
	private final OutputStream out;
	private final Handler handler;
	
	private boolean finished = false;
	
	private int bytesSent = 0;
	
	public ConnectedThreadAndroid(BluetoothSocket sckt_p, Handler handler_p){
		if (D) Log.i(TAG, "Creating ConnectedThread.");
		sckt = sckt_p;
		handler = handler_p;
		
		InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp
        // objects because member streams are final
		try{
			tmpIn = sckt.getInputStream();
			tmpOut = sckt.getOutputStream();
		} catch (Exception e){
			if (D) Log.i(TAG, "Excpetion: couldn't get IO streams.");
			if (D) Log.e(TAG, "Excpetion: couldn't get IO streams.", e);
			this.close();
		}
		
		in = tmpIn;
		out = tmpOut;
			
	}
	
	@Override
	public void run() {
		if (D) Log.i(TAG, "Starting ConnectedThread.");
		byte[] buffer = new byte[1024]; //buffer for reading
		int bytes = 0; //Amount of bytes read
				
		//Loop to read from the socket
		while (!finished){
		
			try {
				bytes = in.read(buffer);
				handler.obtainMessage(pcktTest.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
				
			} catch (Exception e) {
				if (D) Log.i(TAG, "Exception: couldn't receive data. Cause: "+e.getCause().toString());
				if (D) Log.e(TAG, "Exception: couldn't receive data", e);
				
			}
		}
	}
	
	/** 
	 * Send data through the socket
	 * @param str Data that will be sent.
	 */
	public void write(String str){
		byte[] b = str.getBytes();
		bytesSent += b.length;
		try {
			out.write(b, 0, str.length());
			if (D) Log.i(TAG, "Enviou "+b.length+" bytes");
			handler.obtainMessage(pcktTest.MESSAGE_WRITE, bytesSent, -1, b).sendToTarget();
		} catch (Exception e){
			if (D) Log.i(TAG, "Exception: couldn't send data. Mensagem: "+e.getMessage()+" Causa: "+e.getCause().toString());
			if (D) Log.e(TAG, "Exception: couldn't send data.", e);
		}
	}
	
	public void close(){
		try {
			in.close();
			this.flushOut();
			out.close();
			sckt.close();
		} catch (Exception e) {
			if (D) Log.i(TAG, "Exception: couldn't close socket.");
			if (D) Log.e(TAG, "Exception: couldn't close socket.", e);
		}
		finished = true;
	}
	
	public int getBytesSent(){
		return bytesSent;
	}
	
	public void flushOut(){
		try {
			out.flush();
		} catch (IOException e) {}
	}

}
